﻿using System;
using System.Collections.Generic;
using System.Xml.Serialization;

namespace TfL
{
    public interface ILineStatusFeed : ITrackerNetFeed<List<LineStatus>>
    {
        LineStatusFeed IncidentsOnly { get; }
    }

    public class LineStatusFeed : ILineStatusFeed
    {
        public LineStatusFeed(string url, string ns)
            
        {
            _feed = new TrackerNetFeed<List<LineStatus>>(url, ns);
            _feed.DecodeResponse += DecodeResponse;
            Url += "/LineStatus";
        }

        public LineStatusFeed IncidentsOnly
        {
            get
            {
                Url += "/IncidentsOnly";
                return this;
            }
        }

        private void DecodeResponse(System.Net.WebResponse response)
        {
            var serializer = new XmlSerializer(typeof(List<LineStatus>), Ns);
            if (response != null)
            {
                var statusList = (List<LineStatus>)serializer.Deserialize(response.GetResponseStream());
                OnNext(null);
                OnNext(statusList);
                
                
            }
        }

        

        #region ITrackerNetFeed<LineStatus> Members

        public string Ns
        {
            get { return _feed.Ns; }
        }

        public string Url
        {
            get { return _feed.Url; }
            set {_feed.Url = value;}
        }

        #endregion

        #region IObserver<LineStatus> Members

        public void OnCompleted()
        {
            _feed.OnCompleted();
        }

        public void OnError(Exception error)
        {
            _feed.OnError(error);
        }

        public void OnNext(List<LineStatus> value)
        {
            _feed.OnNext(value);
        }

        #endregion

        #region IObservable<LineStatus> Members

        public IDisposable Subscribe(IObserver<List<LineStatus>> observer)
        {
            return _feed.Subscribe(observer);
        }

        #endregion

        #region ITrackerNetFeedPoller<LineStatus> Members

        public System.Reactive.Subjects.ISubject<List<LineStatus>> Poll()
        {
            return _feed.Poll();
        }

        public System.Reactive.Subjects.ISubject<List<LineStatus>> Poll(System.Threading.CancellationToken token, int period)
        {
            return _feed.Poll(token, period);
        }

        #endregion

        private readonly TrackerNetFeed<List<LineStatus>> _feed;

        #region ITrackerNetFeed<LineStatus> Members

        #endregion
    }
}
